import jwt
import datetime
from jwt import exceptions

from django.conf import settings


def get_jwt_token(user_obj, *args, **kwargs):
    """生成jwt token"""
    # 构造headers
    headers = {
        'typ': 'jwt',
        'alg': 'HS256'
    }
    # 构造payload
    payload = {
        'user_id': user_obj.id,
        'username': user_obj.username,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(*args, **kwargs)
    }
    return jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm="HS256", headers=headers)


def check_jwt_code(token):
    try:
        # 从token中获取payload【校验合法性，并获取payload】
        payload = jwt.decode(token, settings.SECRET_KEY, ['HS256'])
        return payload
    except exceptions.ExpiredSignatureError:
        print('token已失效')
        return {'error': 'token已失效'}
    except jwt.DecodeError:
        print('token认证失败')
        return {'error': 'token认证失败'}
    except jwt.InvalidTokenError:
        print('非法的token')
        return {'error': '非法的token'}